import React, { useEffect, useState } from "react";
import styles from "./index.module.less";
import LoginForm from "../../components/LoginForm";
import { useForm } from "antd/es/form/Form";
import { login, userRegister } from "../../server/api";
import { useNavigate } from "react-router-dom";
import { message } from "antd";

const Login: React.FC = ({}) => {
  const navigate = useNavigate();
  const [register, setRegister] = useState(false);
  const [form] = useForm();
  const onFinish = async (values: any) => {
    if (register) {
      await userRegister({ ...values });
      message.success("注册成功");
    } else {
      const res: any = await login({ ...values });
      values.userAccount === "admin"
        ? navigate("/Manage")
        : navigate("/Home");
      localStorage.setItem("token", res.data);
      localStorage.setItem("userId", res.msg);
      message.success("登录成功");
    }
    form.resetFields();
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  useEffect(() => {
    form.resetFields();
  }, [register]);
  return (
    <div className={styles["login-ctn"]}>
      <div className={styles["content"]}>
        <h1 className={styles["title"]}>{register ? "注册" : "登录"}</h1>
        <LoginForm
          form={form}
          register={register}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          setRegister={setRegister}
        />
      </div>
    </div>
  );
};
export default Login;
